package io.renren.utils;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;

public class OpenidToUnionidConverter {

    private static final String APP_ID = "wx22c7cd0dde9319ee";
    private static final String APP_SECRET = "2cad63c304f1d2192ce780b9d61ae5fb";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APP_ID&secret=APP_SECRET&force_refresh=true";
    private static final String GET_UNIONID_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

    public static String getAccessToken(String appId, String appSecret) {
        String url = ACCESS_TOKEN_URL.replace("APP_ID", appId).replace("APP_SECRET", appSecret);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try (Response response = client.newCall(request).execute()) {
            String responseString = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(responseString);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getUnionid(String accessToken, String openid) {
        String url = GET_UNIONID_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openid);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try (Response response = client.newCall(request).execute()) {
            String responseString = response.body().string();
            System.out.println("response___>" + responseString);
            JSONObject jsonObject = JSONObject.parseObject(responseString);
            return jsonObject.getString("unionid");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String accessToken = getAccessToken(APP_ID, APP_SECRET);
        System.out.println("accessToken___>" + accessToken);
        String openid = "olVd4t2Amx_QFRwdtNtp97Bt8Hd4";
        String unionid = getUnionid(accessToken, openid);
        System.out.println("UnionID: " + unionid);
    }
}